///////////////////////////////////////////////////////////////////////////
//
//  @ File      :   res_style.cpp
//  @ Author    :   zhoukaifeng<zhoukaifeng@kingsoft.com>
//  @ DateTime  :   2014-10-26 19:19:31 
//  @ Brief     :
//
///////////////////////////////////////////////////////////////////////////

#include "res_style.h"
#include "res_manager.h"


Style::Style()
{

}

Style::~Style()
{

}

void Style::SetName(const CString& strAttrName, const CString& strValue)
{
    m_strName = strValue;
}

void Style::SetTextColor(const CString& strAttrName, const CString& strValue)
{
    m_dwTextColor = HexStringToDWORD(strValue);
}


DWORD Style::HexStringToDWORD(const CString& strHex)
{
    DWORD dwRes = 0;
    CString strHexTmp = strHex;

    strHexTmp.MakeLower();
    for (int i = 0; i < strHexTmp.GetLength(); ++i)
    {
        if (strHexTmp[i] <= L'9' && strHexTmp[i] >= L'0')
        {
            dwRes = dwRes * 16 + (strHexTmp[i] - L'0');
        }
        else if (strHexTmp[i] <= L'f' && strHexTmp[i] >= L'a')
        {
            dwRes = dwRes * 16 + (strHexTmp[i] - L'a' + 10);
        }
    }
    return dwRes;
}


BOOL StyleManager::LoadStyleFile(const CString& strResID)
{
    CStringA strBuffer;
    BOOL bRet = ResManager::Instance().LoadResource(strResID, strBuffer);

    if (!bRet) return FALSE;

    TiXmlDocument xmlDoc;
    xmlDoc.Parse(strBuffer, NULL, TIXML_ENCODING_UTF8);

    if (xmlDoc.Error()) return FALSE;

    TiXmlElement* rootElement = xmlDoc.RootElement();

    if (strcmp(rootElement->Value(), "style") != 0) return FALSE;

    LPCSTR lpszClassName = NULL;
    for (TiXmlElement* pXmlChild = rootElement->FirstChildElement("class"); pXmlChild != NULL; pXmlChild = pXmlChild->NextSiblingElement("class"))
    {
        lpszClassName = pXmlChild->Attribute("name");
        if (!lpszClassName)
            continue;

        if (m_mapStylePool.find(lpszClassName) == m_mapStylePool.end())
        {
            for (TiXmlAttribute *pAttrib = pXmlChild->FirstAttribute(); NULL != pAttrib; pAttrib = pAttrib->Next())
            {
                m_mapStylePool[lpszClassName].SetAttribute(pAttrib->Name(), pAttrib->Value());
            }
        }
    }
}

BOOL StyleManager::GetStyle(const CString& strClassName, Style& styleObj)
{
    std::map<CString, Style>::iterator it = m_mapStylePool.find(strClassName);
    
    if (it == m_mapStylePool.end()) return FALSE;
    
    styleObj = it->second;

    return TRUE;
}